<?php
namespace app\mobile\controller;

use app\mobile\service\CompanyService;
use app\mobile\service\IncreaseService;
use app\mobile\service\ExportService;
use app\common\model\SystemIncrease;
use app\admin\validate\Increase as IncreaseValidate;
use app\admin\service\IncreaseService as AdmIncService;
use library\Controller;
use think\Db;

/**
 * 增员办理
 * Class Increase
 * @package app\mobile\controller
 */
class Increase extends Base
{
    /**
     * 增员列表
     */
    public function index()
    {        
        $where[] = ['company_id','eq',$this->company['id']];
		$where[] = ['is_deleted','eq',0];
		$status = $this->request->get('status');
        if ($status){
            $where[] = ['status','eq',$status];
        }
		$search =  $this->request->get('search');
		if($search){
			$where[] = ['code|name|id_number','like','%'.$search.'%'];
		}
        $list = SystemIncrease::where($where)
				->field('id,code,name,id_number,mobile,create_at,status')
    			->order('id desc')
    			->limit(10)
    			->select();
    	if($list){
    		foreach($list as $k=>$v){
	    		$list[$k]['create_at'] = date('Y-m-d',strtotime($v['create_at'])); 		
	    	}
    	}		
        $this ->list = $list; 
        $this ->total = Db::name('system_increase')->where(['company_id'=>$this->company['id'],'is_deleted'=>0,'status'=>3])->count();		
        $this->fetch();
    }


    /**
     * 增员列表ajax
     */
    public function page_list()
    {
    	$page = $this->request->post('page');
    	if(!is_numeric($page)){
			$this->error('参数错误');
		}
		$minpage = ($page-1)*10;
		$where[] = ['company_id','eq',$this->company['id']];
		$where[] = ['is_deleted','eq',0];
		$status = $this->request->post('status');
        if ($status){
            $where[] = ['status','eq',$status];
        }
		$search =  $this->request->post('search');
		if($search){
			$where[] = ['code|name|id_number','like','%'.$search.'%'];
		}
        $list = SystemIncrease::where($where)
				->field('id,code,name,id_number,mobile,create_at,status')
    			->order('id desc')
    			->limit($minpage,10)
    			->select();
    	if($list){
    		foreach($list as $k=>$v){
	    		$list[$k]['create_at'] = date('Y-m-d',strtotime($v['create_at'])); 		
	    	}
    	}       	
        $this->success('获取成功',$list);	
		
    }
	
	

	/**
	 * 根据工资获取所有基数
	 */
	public function insuranceAllBase(){
		$wage = $this->request->post('wage');
		if(!is_numeric($wage)){
			$this->error('参数错误');
		}
		$data = IncreaseService::allBase($wage);
		$this->success('获取成功',$data);	
	}
	
	
	/**
	 * 根据工资获取单一基数
	 */
	public function insuranceBase(){
		$wage = $this->request->post('wage');
		$insurance = $this->request->post('insurance');			
		if(!is_numeric($wage) || !in_array($insurance, [1,2,3,4,5])){
			$this->error('参数错误');
		}
		$data = IncreaseService::oneBase($insurance,$wage);
		$this->success('获取成功',$data);
	}
	

	 /**
     * 增员添加
     */
    public function add()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
			trim_array($data);
			$validate = new IncreaseValidate;
    		if(!$validate->scene('examine')->check($data)){
	            $this->error($validate->getError());
	       	}
			$person = Db::name('system_person')->where(['id_number'=>$data['id_number'],'status'=>1])->count();
			if($person){
				$this->error('该用户在职，无法增员');
			}
			$count = Db::name('system_increase')->where(['id_number'=>$data['id_number'],'is_deleted'=>0,'status'=>1])->count();
			if($count){
				$this->error('该用户已增员未审核，无法重复增员');
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status,setmeal_type,people')->find();
			if($contract['status'] == 2){
				$this->error('合同已关闭，无法增员');
			}
			if(in_array($contract['setmeal_type'],[2,3])){
				$person_count = Db::name('system_person')->where(['company_id'=>$this->company['id'],'status'=>1])->count();
				if($person_count >= $contract['people']){
					$this->error('人数套餐已达上限，无法增员');
				}
				$deduction = 0;
				$point = 0; 
			}else{
				$deduction = AdmIncService::deduction_check($this->company['id']);
				if(!$deduction){
					$this->error('服务点不足，无法办理增员');
				}
				$point = Db::name('system_service')->where(['is_special'=>2])->value('point'); 
			}	
			//获取当前账期
			$start_date = service_accounting_period();
			if($start_date != $data['start_date']){
				$this->error('服务账期错误，无法办理增员');
			}
			$insert = [
				'code' => number_rule_max(7),
				'name' => $data['name'],
				'id_number' => $data['id_number'],
				'mobile' => $data['mobile'],
				'company_id' => $this->company['id'],
				'contract_id' => $contract['id'],
				'start_date' => $data['start_date'],
				'wage' => $data['wage'],
				'archives' => $data['archives'],
				'csr_id' => $this->company['csr_id'],
				'source' => 3,
				'deduction' => $deduction,
				'point' => $point
			];
			Db::startTrans();
			$re = Db::name('system_increase')->insertGetId($insert);
			if($re){
				$array = [];
				$insurance = get_option('insurance');
				foreach($insurance as $k=>$v){
		    		$array[$k]['increase_id'] = $re;
					$array[$k]['company_id'] = $this->company['id'];
		    		$array[$k]['insurance'] = $k;
					$array[$k]['csr_id'] = $this->company['csr_id'];
					$array[$k]['contract_id'] = $contract['id'];
		    		if(!empty($data['insurance_status'])){	    			
	    				if(!empty($data['insurance_status'][$k]) && $data['insurance_status'][$k] == 'on'){
	    					$array[$k]['status'] = 1;
	    				}else{
	    					$array[$k]['status'] = 0;
	    				}
		    		}else{
		    			$array[$k]['status'] = 0;
		    		}
					if(!empty($data['insurance_area'])){	    			
	    				if(!empty($data['insurance_area'][$k]) && $data['insurance_area'][$k]){
	    					$array[$k]['area'] = $data['insurance_area'][$k];
	    				}else{
	    					$array[$k]['area'] = 0;
	    				}
		    		}else{
		    			$array[$k]['area'] = 0;
		    		}
		    		if(!empty($data['insurance_start_date'])){	    			
	    				if(!empty($data['insurance_start_date'][$k]) && $data['insurance_start_date'][$k]){
	    					$array[$k]['start_date'] = $data['insurance_start_date'][$k];
	    				}else{
	    					$array[$k]['start_date'] = '';
	    				}
		    		}else{
		    			$array[$k]['start_date'] = '';
		    		}
					if(!empty($data['insurance_wage'])){	    			
	    				if(!empty($data['insurance_wage'][$k]) && $data['insurance_wage'][$k]){
	    					$array[$k]['wage'] = $data['insurance_wage'][$k];
	    				}else{
	    					$array[$k]['wage'] = 0.00;
	    				}
		    		}else{
		    			$array[$k]['wage'] = 0.00;
		    		}
		    		if(!empty($data['company_base'])){	    			
	    				if(!empty($data['company_base'][$k]) && $data['company_base'][$k]){
	    					$array[$k]['company_base'] = $data['company_base'][$k];
	    				}else{
	    					$array[$k]['company_base'] = 0.00;
	    				}
		    		}else{
		    			$array[$k]['company_base'] = 0.00;
		    		}
					if(!empty($data['personal_base'])){	    			
	    				if(!empty($data['personal_base'][$k]) && $data['personal_base'][$k]){
	    					$array[$k]['personal_base'] = $data['personal_base'][$k];
	    				}else{
	    					$array[$k]['personal_base'] = 0.00;
	    				}
		    		}else{
		    			$array[$k]['personal_base'] = 0.00;
		    		}		
		    	}
				$res = Db::name('system_increase_insurance')->insertAll($array);
			}			
			if($re && $res){
				Db::commit();
				save_number_rule_max(7);
				//扣除服务点数或次数
				AdmIncService::deduction($re);
				$this->success('努力提交中......', url('mobile/increase/addSuccess'));
			}else{
                Db::rollback();
                $this->error('提交失败，请稍后再试');
            }
			
    	}else{   		
    		$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status')->find();
			if(!$contract){
				$this->redirect('mobile/publicot/transition', ['info'=>'暂未签订合同，无法增员','type'=>'2']);
			}
			if($contract['status'] == 2){
				$this->redirect('mobile/publicot/transition', ['info'=>'合同已关闭，无法增员','type'=>'2']);
			}
    		$this->insurances = Db::name('system_contract_insurance')->where(['contract_id'=>$contract['id']])->field('insurance,area,status')->select();			
    	}
    	
        $this->fetch();
    }
	
	
	/**
     * 增员编辑
     */
    public function edit()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		trim_array($data);
			$validate = new IncreaseValidate;
    		if(!$validate->scene('examine')->check($data)){
	            $this->error($validate->getError());
	       	}
			$person = Db::name('system_person')->where(['id_number'=>$data['id_number'],'status'=>1])->count();
			if($person){
				$this->error('该用户在职，无法增员');
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status')->find();
			if($contract['status'] == 2){
				$this->error('合同已关闭，无法增员');
			}
			Db::name('system_increase')->where(['id'=>$data['id']])->update(['name'=>$data['name'],'id_number'=>$data['id_number'],'mobile'=>$data['mobile'],'start_date'=>$data['start_date'],'wage'=>$data['wage'],'archives'=>$data['archives'],'status'=>1]);
			$insurance = get_option('insurance');
	    	foreach($insurance as $k=>$v){
	    		if(!empty($data['insurance_status'])){	    			
    				if(!empty($data['insurance_status'][$k]) && $data['insurance_status'][$k] == 'on'){
    					$array['status'] = 1;
    				}else{
    					$array['status'] = 0;
    				}
	    		}else{
	    			$array['status'] = 0;
	    		}
				if(!empty($data['insurance_area'])){	    			
    				if(!empty($data['insurance_area'][$k]) && $data['insurance_area'][$k]){
    					$array['area'] = $data['insurance_area'][$k];
    				}else{
    					$array['area'] = 0;
    				}
	    		}else{
	    			$array['area'] = 0;
	    		}
	    		if(!empty($data['insurance_start_date'])){	    			
    				if(!empty($data['insurance_start_date'][$k]) && $data['insurance_start_date'][$k]){
    					$array['start_date'] = $data['insurance_start_date'][$k];
    				}else{
    					$array['start_date'] = '';
    				}
	    		}else{
	    			$array['start_date'] = '';
	    		}
				if(!empty($data['insurance_wage'])){	    			
    				if(!empty($data['insurance_wage'][$k]) && $data['insurance_wage'][$k]){
    					$array['wage'] = $data['insurance_wage'][$k];
    				}else{
    					$array['wage'] = 0.00;
    				}
	    		}else{
	    			$array['wage'] = 0.00;
	    		}
				if(!empty($data['company_base'])){	    			
    				if(!empty($data['company_base'][$k]) && $data['company_base'][$k]){
    					$array['company_base'] = $data['company_base'][$k];
    				}else{
    					$array['company_base'] = 0.00;
    				}
	    		}else{
	    			$array['company_base'] = 0.00;
	    		}
				if(!empty($data['personal_base'])){	    			
    				if(!empty($data['personal_base'][$k]) && $data['personal_base'][$k]){
    					$array['personal_base'] = $data['personal_base'][$k];
    				}else{
    					$array['personal_base'] = 0.00;
    				}
	    		}else{
	    			$array['personal_base'] = 0.00;
	    		}
				Db::name('system_increase_insurance')->where(['increase_id'=>$data['id'],'insurance'=>$k])->update($array);	    				
	    	}
			$this->success('努力提交中......', url('mobile/increase/addSuccess'));
    	}else{
    		$id = $this->request->get('id');
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status')->find();
			if($contract['status'] == 2){
				$this->redirect('mobile/publicot/transition', ['info'=>'合同已关闭，无法编辑','type'=>'2']);
			}
			$increase = Db::name('system_increase')->where(['id'=>$id,'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->redirect('mobile/publicot/transition', ['info'=>'暂无员工信息','type'=>'2']);
			}
			$this->increase = $increase;
			$increase_insurance = Db::name('system_increase_insurance')->where(['increase_id'=>$id])->field('insurance,area,status,wage,start_date,company_base,personal_base')->select();
			foreach($increase_insurance as $k=>$v){
				if($v['company_base'] == 0.00){
					$increase_insurance[$k]['company_base'] = '';
				}
				if($v['personal_base'] == 0.00){
					$increase_insurance[$k]['personal_base'] = '';
				}
				if($v['wage'] == 0.00){
					$increase_insurance[$k]['wage'] = '';
				}
			}
			$this->increase_insurance = $increase_insurance;
			$this->insurances = Db::name('system_contract_insurance')->where(['contract_id'=>$contract['id']])->field('insurance,area,status')->select();	
					
    	}
        $this->fetch();
    }
    
    
    
    /**
     * 增员反馈
     */
    public function feedback()
    {
    	if($this->request->isPost()){
    		$data = $this->request->post();
    		trim_array($data);
			$validate = new IncreaseValidate;
    		if(!$validate->scene('examine')->check($data)){
	            $this->error($validate->getError());
	       	}
			$person = Db::name('system_person')->where(['id_number'=>$data['id_number'],'status'=>1])->count();
			if($person){
				$this->error('该用户在职，无法增员');
			}
			$count = Db::name('system_increase')->where(['id_number'=>$data['id_number'],'is_deleted'=>0,'status'=>1])->count();
			if($count){
				$this->error('该用户已增员未审核，无法重复增员');
			}
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status,setmeal_type,people')->find();
			if($contract['status'] == 2){
				$this->error('合同已关闭，无法增员');
			}
			if(in_array($contract['setmeal_type'],[2,3])){
				$person_count = Db::name('system_person')->where(['company_id'=>$this->company['id'],'status'=>1])->count();
				if($person_count >= $contract['people']){
					$this->error('人数套餐已达上限，无法增员');
				}
				$deduction = 0;
				$point = 0; 
			}else{
				$deduction = AdmIncService::deduction_check($this->company['id']);
				if(!$deduction){
					$this->error('服务点不足，无法办理增员');
				}
				$point = Db::name('system_service')->where(['is_special'=>2])->value('point'); 
			}
			Db::name('system_increase')->where(['id'=>$data['id']])->update(['name'=>$data['name'],'id_number'=>$data['id_number'],'mobile'=>$data['mobile'],'start_date'=>$data['start_date'],'wage'=>$data['wage'],'archives'=>$data['archives'],'status'=>1,'deduction'=>$deduction]);
			$insurance = get_option('insurance');
	    	foreach($insurance as $k=>$v){
	    		if(!empty($data['insurance_status'])){	    			
    				if(!empty($data['insurance_status'][$k]) && $data['insurance_status'][$k] == 'on'){
    					$array['status'] = 1;
    				}else{
    					$array['status'] = 0;
    				}
	    		}else{
	    			$array['status'] = 0;
	    		}
				if(!empty($data['insurance_area'])){	    			
    				if(!empty($data['insurance_area'][$k]) && $data['insurance_area'][$k]){
    					$array['area'] = $data['insurance_area'][$k];
    				}else{
    					$array['area'] = 0;
    				}
	    		}else{
	    			$array['area'] = 0;
	    		}
	    		if(!empty($data['insurance_start_date'])){	    			
    				if(!empty($data['insurance_start_date'][$k]) && $data['insurance_start_date'][$k]){
    					$array['start_date'] = $data['insurance_start_date'][$k];
    				}else{
    					$array['start_date'] = '';
    				}
	    		}else{
	    			$array['start_date'] = '';
	    		}
				if(!empty($data['insurance_wage'])){	    			
    				if(!empty($data['insurance_wage'][$k]) && $data['insurance_wage'][$k]){
    					$array['wage'] = $data['insurance_wage'][$k];
    				}else{
    					$array['wage'] = 0.00;
    				}
	    		}else{
	    			$array['wage'] = 0.00;
	    		}
				if(!empty($data['company_base'])){	    			
    				if(!empty($data['company_base'][$k]) && $data['company_base'][$k]){
    					$array['company_base'] = $data['company_base'][$k];
    				}else{
    					$array['company_base'] = 0.00;
    				}
	    		}else{
	    			$array['company_base'] = 0.00;
	    		}
				if(!empty($data['personal_base'])){	    			
    				if(!empty($data['personal_base'][$k]) && $data['personal_base'][$k]){
    					$array['personal_base'] = $data['personal_base'][$k];
    				}else{
    					$array['personal_base'] = 0.00;
    				}
	    		}else{
	    			$array['personal_base'] = 0.00;
	    		}
				Db::name('system_increase_insurance')->where(['increase_id'=>$data['id'],'insurance'=>$k])->update($array);	    				
	    	}
	    	//扣除服务点数或次数
			AdmIncService::deduction($data['id']);
			$this->success('努力提交中......', url('mobile/increase/addSuccess'));
    	}else{
    		$id = $this->request->get('id');
			$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id']])->order('id desc')->field('id,status')->find();
			if($contract['status'] == 2){
				$this->redirect('mobile/publicot/transition', ['info'=>'合同已关闭，无法编辑','type'=>'2']);
			}
			$increase = Db::name('system_increase')->where(['id'=>$id,'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
			if(!$increase){
				$this->redirect('mobile/publicot/transition', ['info'=>'暂无员工信息','type'=>'2']);
			}
			$this->increase = $increase;
			$increase_insurance = Db::name('system_increase_insurance')->where(['increase_id'=>$id])->field('insurance,area,status,wage,start_date,company_base,personal_base')->select();
			foreach($increase_insurance as $k=>$v){
				if($v['company_base'] == 0.00){
					$increase_insurance[$k]['company_base'] = '';
				}
				if($v['personal_base'] == 0.00){
					$increase_insurance[$k]['personal_base'] = '';
				}
				if($v['wage'] == 0.00){
					$increase_insurance[$k]['wage'] = '';
				}
			}
			$this->increase_insurance = $increase_insurance;
			$this->insurances = Db::name('system_contract_insurance')->where(['contract_id'=>$contract['id']])->field('insurance,area,status')->select();	
					
    	}
        $this->fetch();
    }
    
	
	/**
     * 增员查看
     */
    public function view()
    {
    	$id = $this->request->get('id');
		$increase = Db::name('system_increase')->where(['id'=>$id,'company_id'=>$this->company['id'],'is_deleted'=>0])->find();
		if(!$increase){
			$this->redirect('mobile/publicot/transition', ['info'=>'暂无员工信息','type'=>'2']);
		}
		$increase_insurance = Db::name('system_increase_insurance')->where(['increase_id'=>$id])->field('insurance,area,status,wage,start_date,company_base,personal_base')->select();
		foreach($increase_insurance as $k=>$v){
			if($v['company_base'] == 0.00){
				$increase_insurance[$k]['company_base'] = '';
			}
			if($v['personal_base'] == 0.00){
				$increase_insurance[$k]['personal_base'] = '';
			}
			if($v['wage'] == 0.00){
				$increase_insurance[$k]['wage'] = '';
			}
		}
		$this->increase_insurance = $increase_insurance;
		$this->increase = $increase;
        $this->fetch();
    }


	/**
     * 增员成功
     */
    public function addSuccess()
    {
        $this->fetch();
    }
	
	
	/**
     * 增员导入
     */
    public function import()
    {
        $this->fetch();
    }
	
	
	/**
     * 导入结果
     */
    public function importResult()
    {
        $this->fetch();
    }
	
	
	/**
     * 增员删除
     */
    public function del()
    {
    	$ids = $this->request->post('ids');
		if(!$ids){
			$this->error('请选则数据');
		}
		$ids = explode(',', $ids);
		$count = Db::name('system_increase')->where(['id'=>$ids,'status'=>2])->count();
		if($count){
			$this->error('所选项中包含已审核数据，请刷新后重试');
		}
		Db::startTrans();
		$re = Db::name('system_increase')->where(['id'=>$ids])->update(['is_deleted'=>1]);
        $res = Db::name('system_increase_insurance')->where(['increase_id'=>$ids])->update(['is_deleted'=>1]);
		if($re && $res){
			//返还点数或次数
//			AdmIncService::deduction_back($ids);
			Db::commit();
			$this->success('删除成功');
		}else{
            Db::rollback();
            $this->error('删除失败，请刷新后重试');
        }
    }
	
	
	/**
     * 导出
     */
    public function export()
    {
        $data = $this->request->param();
    	$ids = explode(',', $data['id']);
		$list = ExportService::export_increase($ids,$this->company['id']);
    	toexcel($list['filename'],$list['titles'],$list['list']);  
    }
	
	
	/**
     * 下载模板
     */
	public function download()
    {			
		file_download('增员导入表.xls','static/admin/excel/comincimport.xls');		
    }
	
	
	/**
     * 导出错误
     */
	public function exporterr()
    {
    	$data = $this->request->param();
		$list = cache($data['list']);
		if($list){
			foreach($list as $k=>$v){
				$list[$k]['idcard'] = ' '.$v['idcard'];
			}
		}		
		$filename = '错误结果列表';
		$titles = array(
            array('name','姓名'),
            array('idcard','身份证号'),
            array('msg','错误原因')
        );	
		
		toexcel($filename,$titles,$list);  	
    }
	
	
	/**
     * 增员导入
     */  
	public function upload(){
	    // 获取表单上传文件 例如上传了001.jpg
	    $file = request()->file('file');
		//查看公司合同状态是否正常
		$contract = Db::name('system_contract')->where(['company_id'=>$this->company['id'],'status'=>1])->find();	
		if(!$contract){
			$this->error('暂无合同或合同状态异常，无法导入');
		}
		if (empty($file) || !$file) {
            $this->error('文件上传异常，文件可能过大或未上传');
       	} 
		if (!$file->checkExt('xls')) {
			$this->error('文件类型错误');
        }
        if ($file->checkExt('php,sh')) {
			$this->error('可执行文件禁止上传');
        }
        if (!$file->checkSize(8388608)) {
			$this->error('文件过大，不能大于8M');
        }	
		$path = 'upload/annex/';
        if(!file_exists($path)){
            mkdir($path,0777,true);
        }
		$realName = $file->getInfo()['name'];
	    $info = $file->move($path);
	    if($info){
	    	$enclosure['exts'] = $info->getExtension();
	        $enclosure['filename'] = $path.$info->getSaveName();			
			$arr = import_excel($enclosure);
			if(!isset($arr)||empty($arr)){
	            $this->error('导入数据不能为空');
	        }
	        if(count($arr) > 500 ){
	            $this->error('超过导入限制500条');
	        }
			$re = IncreaseService::import_increase($arr,$contract);
			$suss_num = count($re['suss']);
			$err_num = count($re['err']);
			if($err_num){
				$cache_name = randomStr('import');
				cache($cache_name, $re['err'], 86400);
			}else{
				$cache_name = '';
			}
			
			$this->success('导入成功',['suss_num'=>$suss_num,'err_num'=>$err_num,'err_file'=>$cache_name]);	
	    }else{
	        // 上传失败获取错误信息
	        $this->error($file->getError());
	    }
	}
}
